package validate

import (
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	en_translations "github.com/go-playground/validator/v10/translations/zh"
)

type Validate struct {
	validator *validator.Validate
	trans     ut.Translator
	errs      validator.ValidationErrors
}

func Default() (*Validate, error) {
	validate := &Validate{}
	validate.validator = validator.New()
	lang := zh.New()
	uni := ut.New(lang, lang)
	trans, _ := uni.GetTranslator("zh")
	validate.SetTrans(trans)
	err := validate.registerDefaultTranslations(validate.trans)
	return validate, err
}

func (c *Validate) SetTrans(trans ut.Translator) {
	c.trans = trans
}

func (c *Validate) registerDefaultTranslations(trans ut.Translator) error {
	return en_translations.RegisterDefaultTranslations(c.validator, trans)
}

func (c *Validate) CheckStruct(s interface{}) bool {
	err := c.validator.Struct(s)
	if err != nil {
		c.errs = err.(validator.ValidationErrors)
		return false
	}
	return true
}

func (c *Validate) GetAllError() []string {
	var errList []string
	for _, e := range c.errs {
		// can translate each error one at a time.
		errList = append(errList, e.Translate(c.trans))
	}
	return errList
}

func (c *Validate) GetOneError() string {
	for _, e := range c.errs {
		// can translate each error one at a time.
		return e.Translate(c.trans)
	}
	return ""
}
